<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<view class="nav-bar">
			<view class="status-bar" :style="{height: statusBarHeight + 'px'}"></view>
			<view class="nav-content">
				<view class="nav-left" @click="goBack">
					<u-icon name="arrow-left" color="#333" size="18"></u-icon>
				</view>
				<view class="nav-title">认养详情</view>
				<view class="nav-right"></view>
			</view>
		</view>
		
		<!-- 主内容区域 -->
		<view class="main-content" :style="{paddingTop: (statusBarHeight + 44) + 'px'}">
			<!-- 项目图片/视频区域 -->
			<view class="media-section">
				<view class="media-container">
					<image v-if="currentMediaType === 'image'" class="project-image" :src="projectInfo.image" mode="aspectFill"></image>
					<video v-else class="project-video" :src="projectInfo.video" controls></video>
				</view>
				<view class="media-type-tabs">
					<view class="tab-item" :class="{ active: currentMediaType === 'image' }" @click="switchMediaType('image')">图片</view>
					<view class="tab-item" :class="{ active: currentMediaType === 'video' }" @click="switchMediaType('video')">视频</view>
				</view>
			</view>
			
			<!-- 项目基本信息 -->
			<view class="project-info">
				<view class="price">¥ {{projectInfo.price}}</view>
				<view class="title">{{projectInfo.title}}</view>
				<view class="subtitle">{{projectInfo.subtitle}}</view>
			</view>
			
			<!-- 项目特点 -->
			<view class="project-features">
				<view class="section-title">项目特点</view>
				<view class="features-grid">
					<view class="feature-item">
						<u-icon name="tags" color="#4CAF50" size="24"></u-icon>
						<view class="feature-label">{{projectInfo.productType}}</view>
						<view class="feature-value">预估产品</view>
					</view>
					<view class="feature-item">
						<u-icon name="list-dot" color="#4CAF50" size="24"></u-icon>
						<view class="feature-label">{{projectInfo.totalArea}}</view>
						<view class="feature-value">剩余数量</view>
					</view>
					<view class="feature-item">
						<u-icon name="clock" color="#4CAF50" size="24"></u-icon>
						<view class="feature-label">{{projectInfo.period}}</view>
						<view class="feature-value">认领周期</view>
					</view>
					<view class="feature-item">
						<u-icon name="car" color="#4CAF50" size="24"></u-icon>
						<view class="feature-label">每季配送</view>
						<view class="feature-value">认养收获</view>
					</view>
				</view>
			</view>
			
			<!-- 认养流程 -->
			<view class="adopt-process">
				<view class="section-title">认养流程</view>
				<view class="process-list">
					<view class="process-item">
						<view class="process-icon">
							<u-icon name="calendar" color="#4CAF50" size="24"></u-icon>
						</view>
						<view class="process-content">
							<view class="process-title">认养下单</view>
							<view class="process-desc">认养下单并成功支付</view>
						</view>
					</view>
					<view class="process-item">
						<view class="process-icon">
							<u-icon name="eye" color="#4CAF50" size="24"></u-icon>
						</view>
						<view class="process-content">
							<view class="process-title">认养过程</view>
							<view class="process-desc">认养过程可以实时观看基地视频监控以及物联网环境实时数据</view>
						</view>
					</view>
					<view class="process-item">
						<view class="process-icon">
							<u-icon name="car" color="#4CAF50" size="24"></u-icon>
						</view>
						<view class="process-content">
							<view class="process-title">认养收货</view>
							<view class="process-desc">认养成熟可以自提，或农场鲜鲜配合第三方冷链快递配送到家</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 认养详情 -->
			<view class="adopt-details">
				<view class="detail-item">
					<text class="detail-label">认养类型：</text>
					<text class="detail-value">{{projectInfo.adoptType}}</text>
				</view>
				<view class="detail-item">
					<text class="detail-label">截止时间：</text>
					<text class="detail-value">{{projectInfo.deadline}}</text>
				</view>
				<view class="detail-item">
					<text class="detail-label">购买数量：</text>
					<view class="quantity-control">
						<u-icon name="minus" @click="decreaseQuantity" size="16"></u-icon>
						<input class="quantity-input" v-model="quantity" type="number" />
						<u-icon name="plus" @click="increaseQuantity" size="16"></u-icon>
					</view>
				</view>
				<view class="detail-item checkbox-item">
					<u-checkbox-group v-model="checkboxValue" @change="onCheckboxChange">
						<u-checkbox 
							:customStyle="{marginBottom: '8px'}"
							name="protocol"
							:labelDisabled="true"
							:disabled="!protocolConfirmed"
							label="阅读并同意"
						>
						</u-checkbox>
					</u-checkbox-group>
					<text class="protocol-link" @click="showProtocol">《认养协议》</text>
				</view>
			</view>
			
			<!-- 认养详情说明 -->
			<view class="adopt-description">
				<view class="section-title">认养详情</view>
				<view class="description-content">
					<text>{{projectInfo.description}}</text>
				</view>
			</view>
		</view>
		
		<!-- 认养协议弹出层 -->
		<u-popup :show="protocolVisible" mode="bottom" :round="20" @close="closeProtocol" :safe-area-inset-bottom="true">
			<view class="protocol-popup">
				<view class="protocol-header">
					<view class="protocol-title">《认养协议》</view>
					<u-icon name="close" @click="closeProtocol" size="20" color="#999"></u-icon>
				</view>
				<scroll-view 
					class="protocol-content" 
					scroll-y 
					@scroll="onProtocolScroll"
					@scrolltolower="onScrollToLower"
					:scroll-top="scrollTop"
					lower-threshold="50"
				>
					<view class="protocol-text">
						<text v-for="(line, index) in protocolLines" :key="index" class="protocol-line">
							{{ line }}
						</text>
					</view>
				</scroll-view>
				<view class="protocol-footer">
					<view 
						class="confirm-btn" 
						:class="{ disabled: !canConfirm }"
						@click="confirmProtocol"
					>
						我已阅读并知晓本协议
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 底部导航栏 -->
		<view class="bottom-nav">
			<view class="nav-item" @click="goHome">
				<u-icon name="home" size="20"></u-icon>
				<text>首页</text>
			</view>
			<view class="nav-item" @click="shareProject">
				<u-icon name="share" size="20"></u-icon>
				<text>分享</text>
			</view>
			<view class="nav-item" @click="collectProject">
				<u-icon name="heart" :color="isCollected ? '#FF5722' : '#999'" size="20"></u-icon>
				<text>收藏</text>
			</view>
			<view class="adopt-now-btn" @click="adoptNow">立即认养</view>
		</view>
	</view>
</template>

<script>
	import request from '@/util/request.js';
	
	export default {
		data() {
			return {
				statusBarHeight: 0,
				quantity: 1,
				checkboxValue: [],
				isCollected: false,
				projectInfo: {
					id: null,
					title: "",
					subtitle: "",
					price: "",
					image: "",
					video: "",
					productType: "",
					totalArea: "",
					period: "",
					adoptType: "",
					deadline: "",
					description: ""
				},
				currentMediaType: 'image', // 当前媒体类型：image/video
				// 协议相关
				protocolVisible: false,
				protocolContent: '',
				protocolLines: [],
				canConfirm: false,
				scrollTop: 0,
				protocolConfirmed: false, // 标记协议是否已确认
				// 媒体文件URL前缀
				mediaUrlPrefix: 'http://121.36.197.175:19000/test/'
			}
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},
			
			// 返回首页
			goHome() {
				uni.switchTab({
					url: '/pages/home/home'
				});
			},
			
			// 分享项目
			shareProject() {
				uni.showToast({
					title: '分享功能还没做',
					icon: 'none'
				});
			},
			
			// 收藏项目
			collectProject() {
				this.isCollected = !this.isCollected;
				uni.showToast({
					title: this.isCollected ? '收藏成功' : '取消收藏',
					icon: 'none'
				});
			},
			
			// 立即认养
			adoptNow() {
				if (!this.checkboxValue.includes('protocol')) {
					uni.showToast({
						title: '请先同意认养协议',
						icon: 'none'
					});
					return;
				}
				
				// 提取认养周期的数字部分
				let periodDays = 0;
				if (this.projectInfo.period) {
					// 使用正则表达式提取数字部分，并转换为整型
					const match = this.projectInfo.period.match(/\d+/);
					periodDays = match ? parseInt(match[0]) : 0;
				}
				
				// 跳转到订单信息页面，传递商品信息和购买数量
				const params = {
					id: this.projectInfo.id,
					title: encodeURIComponent(this.projectInfo.title),
					price: this.projectInfo.price,
					image: encodeURIComponent(this.projectInfo.image),
					quantity: this.quantity,
					periodDays: periodDays // 传递认养周期天数
				};
				
				const queryString = Object.keys(params).map(key => `${key}=${params[key]}`).join('&');
				
				uni.navigateTo({
					url: `/pages/farm/orderInfo?${queryString}`
				});
			},
			
			// 减少数量
			decreaseQuantity() {
				if (this.quantity > 1) {
					this.quantity--;
				}
			},
			
			// 增加数量
			increaseQuantity() {
				this.quantity++;
			},
			
			// 切换媒体类型
			switchMediaType(type) {
				this.currentMediaType = type;
			},
			
			// 获取认养详情
			async loadAdoptDetail(adoptId) {
				try {
					uni.showLoading({
						title: '加载中...'
					});
					
					const response = await request({
						url: `/adopt-service/adopt/detail/${adoptId}`,
						method: 'GET'
					});
					
					if (response.code === 200 && response.data.adoptDetail) {
						const detail = response.data.adoptDetail;
						
						// 处理图片和视频URL，如果不是完整URL则添加前缀
						const processUrl = (url) => {
							if (!url) return '';
							if (url.startsWith('http://') || url.startsWith('https://')) {
								return url;
							}
							return this.mediaUrlPrefix + url;
						};
						
						// 更新项目信息
						this.projectInfo = {
							id: detail.id,
							title: detail.title || '',
							subtitle: detail.subtitle || '',
							price: detail.price || '0.00',
							image: processUrl(detail.image),
							video: processUrl(detail.video),
							productType: detail.productType || '',
							totalArea: detail.totalArea || '',
							period: detail.period || '',
							adoptType: detail.adoptType || '',
							deadline: detail.deadline || '',
							description: detail.description || ''
						};
						
						console.log('认养详情加载成功:', this.projectInfo);
					} else {
						uni.showToast({
							title: response.message || '获取认养详情失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取认养详情失败:', error);
					uni.showToast({
						title: '获取认养详情失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			
			// 复选框变化处理
			onCheckboxChange(names) {
				// 如果未阅读协议就尝试勾选
				if (names.length > 0 && !this.protocolConfirmed) {
					uni.showToast({
						title: '请先阅读认养协议',
						icon: 'none'
					});
					this.showProtocol(); // 自动打开协议弹窗
					return;
				}
			},
			
			// 显示协议弹出层
			async showProtocol() {
				this.protocolVisible = true;
				this.canConfirm = false;
				this.scrollTop = 0;
				
				// 如果还没有加载协议内容，则获取
				if (!this.protocolContent) {
					await this.loadProtocol();
				}
			},
			
			// 获取协议内容
			async loadProtocol() {
				try {
					const response = await request({
						url: '/adopt-service/adopt/protocol',
						method: 'GET'
					});
					
					if (response.code === 200 && response.data.protocol) {
						this.protocolContent = response.data.protocol.protocolInfo;
						// 处理换行符，将\n和\\n都转换为换行
						const lines = this.protocolContent
							.replace(/\\n/g, '\n')  // 先处理\\n
							.split('\n')            // 按\n分割
							.filter(line => line.trim() !== ''); // 过滤空行
						this.protocolLines = lines;
					}
				} catch (error) {
					console.error('获取协议内容失败:', error);
					uni.showToast({
						title: '获取协议内容失败',
						icon: 'none'
					});
				}
			},
			
			// 关闭协议弹出层
			closeProtocol() {
				this.protocolVisible = false;
				this.canConfirm = false; // 重置确认状态
			},
			
			// 监听协议内容滚动
			onProtocolScroll(e) {
				const { scrollTop, scrollHeight } = e.detail;
				// 获取scroll-view的高度
				const query = uni.createSelectorQuery().in(this);
				query.select('.protocol-content').boundingClientRect((data) => {
					if (data) {
						const clientHeight = data.height;
						// 当滚动到底部时允许确认（留一些容差）
						this.canConfirm = scrollTop + clientHeight >= scrollHeight - 20;
					}
				}).exec();
			},
			
			// 滚动到底部事件
			onScrollToLower() {
				this.canConfirm = true;
			},
			
			// 确认协议
			confirmProtocol() {
				if (!this.canConfirm) {
					uni.showToast({
						title: '请先阅读完整协议内容',
						icon: 'none'
					});
					return;
				}
				
				// 设置协议确认状态和复选框状态
				this.protocolConfirmed = true;
				this.checkboxValue = ['protocol'];
				
				// 关闭弹出层
				this.protocolVisible = false;
				
				uni.showToast({
					title: '已同意认养协议',
					icon: 'success'
				});
			}
		},
		onLoad(options) {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;
			
			// 如果有传递参数，可以在这里接收
			if (options.id) {
				console.log('项目ID:', options.id);
				// 根据ID获取项目详情
				this.loadAdoptDetail(options.id);
			} else {
				// 如果没有传递ID，显示错误提示
				uni.showToast({
					title: '缺少认养项目ID',
					icon: 'none'
				});
				
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		}
	}
</script>

<style scoped>
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 120rpx;
	}
	
	/* 自定义导航栏 */
	.nav-bar {
		background-color: #ffffff;
		border-bottom: 1rpx solid #f0f0f0;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1000;
	}
	
	.status-bar {
		width: 100%;
		background-color: #ffffff;
	}
	
	.nav-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 88rpx;
		padding: 0 30rpx;
		background-color: #ffffff;
	}
	
	.nav-left {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}
	
	.nav-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		flex: 1;
	}
	
	.nav-right {
		width: 60rpx;
		flex-shrink: 0;
	}
	
	/* 主内容区域 */
	.main-content {
		/* padding-top 通过内联样式动态设置，包含状态栏高度 */
	}
	
	/* 媒体区域 */
	.media-section {
		background-color: #ffffff;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
	}
	
	.media-container {
		position: relative;
		height: 400rpx;
		margin-bottom: 20rpx;
	}
	
	.project-image,
	.project-video {
		width: 100%;
		height: 100%;
		background-color: #f5f5f5;
	}
	
	.media-type-tabs {
		display: flex;
		justify-content: center;
		padding: 0 30rpx;
	}
	
	.tab-item {
		padding: 10rpx 40rpx;
		color: #666;
		font-size: 28rpx;
		transition: all 0.3s;
		position: relative;
		margin: 0 20rpx;
	}
	
	.tab-item.active {
		color: #4CAF50;
	}
	
	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 4rpx;
		background-color: #4CAF50;
		border-radius: 2rpx;
	}
	
	/* 项目信息 */
	.project-info {
		background-color: #ffffff;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}
	
	.price {
		color: #FF5722;
		font-size: 48rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		color: #333;
	}
	
	.subtitle {
		font-size: 28rpx;
		color: #999;
	}
	
	/* 项目特点 */
	.project-features {
		background-color: #ffffff;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
		color: #333;
	}
	
	.features-grid {
		display: flex;
		flex-wrap: wrap;
	}
	
	.feature-item {
		width: 50%;
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}
	
	.feature-label {
		font-size: 32rpx;
		font-weight: bold;
		margin-left: 15rpx;
		color: #333;
	}
	
	.feature-value {
		font-size: 24rpx;
		color: #999;
		margin-left: 10rpx;
	}
	
	/* 认养流程 */
	.adopt-process {
		background-color: #ffffff;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}
	
	.process-list {
		
	}
	
	.process-item {
		display: flex;
		align-items: flex-start;
		margin-bottom: 30rpx;
	}
	
	.process-item:last-child {
		margin-bottom: 0;
	}
	
	.process-icon {
		width: 80rpx;
		height: 80rpx;
		background-color: #f0f8f0;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		flex-shrink: 0;
	}
	
	.process-content {
		flex: 1;
	}
	
	.process-title {
		font-size: 28rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		color: #333;
	}
	
	.process-desc {
		font-size: 24rpx;
		color: #666;
		line-height: 1.5;
	}
	
	/* 认养详情 */
	.adopt-details {
		background-color: #ffffff;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}
	
	.detail-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		font-size: 28rpx;
	}
	
	.detail-item:last-child {
		margin-bottom: 0;
	}
	
	.detail-label {
		color: #333;
		margin-right: 20rpx;
	}
	
	.detail-value {
		color: #666;
	}
	
	.quantity-control {
		display: flex;
		align-items: center;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		overflow: hidden;
	}
	
	.quantity-input {
		width: 80rpx;
		height: 60rpx;
		text-align: center;
		border: none;
		font-size: 28rpx;
	}
	
	.quantity-control .u-icon {
		padding: 20rpx;
		background-color: #f5f5f5;
	}
	
	/* 复选框样式 */
	.checkbox-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
	}
	
	.protocol-link {
		color: #4CAF50;
		font-size: 28rpx;
		margin-left: 10rpx;
	}
	
	/* 认养描述 */
	.adopt-description {
		background-color: #ffffff;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}
	
	.description-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
	}
	
	/* 底部导航栏 */
	.bottom-nav {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 120rpx;
		background-color: #ffffff;
		border-top: 1rpx solid #f0f0f0;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		z-index: 1000;
	}
	
	.nav-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-right: 40rpx;
	}
	
	.nav-item text {
		font-size: 20rpx;
		color: #999;
		margin-top: 5rpx;
	}
	
	.adopt-now-btn {
		flex: 1;
		background-color: #4CAF50;
		color: #ffffff;
		text-align: center;
		line-height: 80rpx;
		border-radius: 40rpx;
		font-size: 32rpx;
		font-weight: bold;
	}
	
	/* 协议链接样式 */
	.protocol-link {
		color: #4CAF50;
		text-decoration: underline;
	}
	
	/* 协议弹出层样式 */
	.protocol-popup {
		background-color: #ffffff;
		border-radius: 20rpx 20rpx 0 0;
		height: 80vh;
		display: flex;
		flex-direction: column;
		width: 100%;
		max-width: 100vw;
		box-sizing: border-box;
	}
	
	.protocol-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		flex-shrink: 0;
	}
	
	.protocol-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.protocol-content {
		flex: 1;
		padding: 0 30rpx;
		overflow-y: auto;
		box-sizing: border-box;
	}
	
	.protocol-text {
		padding: 20rpx 0;
		width: 100%;
		box-sizing: border-box;
	}
	
	.protocol-line {
		display: block;
		font-size: 28rpx;
		line-height: 1.6;
		color: #666;
		margin-bottom: 20rpx;
		word-wrap: break-word;
		word-break: break-all;
		white-space: pre-wrap;
		width: 100%;
		max-width: calc(100vw - 120rpx);
		overflow-wrap: break-word;
		box-sizing: border-box;
		overflow: hidden;
	}
	
	.protocol-footer {
		padding: 30rpx;
		border-top: 1rpx solid #f0f0f0;
		flex-shrink: 0;
	}
	
	.confirm-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 40rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: #ffffff;
		background-color: rgb(102, 202, 77);
		transition: all 0.3s;
	}
	
	.confirm-btn.disabled {
		background-color: #cccccc;
		color: #999999;
	}
</style> 